package pki;

import org.apache.log4j.Logger;
import pki.util.Hex;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class Relay
        extends Thread {

    private Logger logger = Logger.getLogger(Relay.class);

    static final int BUFSIZ = 1000;
    InputStream in;
    OutputStream out;
    byte[] buf = new byte[1000];
    String name;
    int tag;

    ByteArrayOutputStream bous = new ByteArrayOutputStream();

    Relay(String name, int tag, InputStream paramInputStream, OutputStream paramOutputStream) {
        this.name = name;
        this.tag = tag;
        this.in = paramInputStream;
        this.out = paramOutputStream;
    }

    public void run() {
        try {
            if(tag > 0) {
                this.out.write(tag);
                bous.write(tag);
            }

            int i;
            while ((i = this.in.read(this.buf)) > 0) {
                this.out.write(this.buf, 0, i);
                this.out.flush();

                // process buf
                bous.write(buf, 0, i);
            }
        } catch (Throwable ex) {
        } finally {
            try {
                this.in.close();
                this.out.close();

                byte[] data = bous.toByteArray();
                bous.close();

                StringBuffer logStr = new StringBuffer("\n");
                logStr.append("[" + this.name + " original data](" + data.length + ")" + "\n");
                logStr.append(new String(Hex.encode(data)) + "\n");
                logger.info(logStr.toString());

            } catch (Throwable ex2) {
            }
        }
    }


}
